package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.api.content.model.dto.CourseBaseDTO;
import com.xuecheng.api.content.model.qo.QueryCourseBaseModel;
import com.xuecheng.api.content.model.vo.CourseAuditVO;
import com.xuecheng.common.domain.code.CommonErrorCode;
import com.xuecheng.common.domain.page.PageRequestParams;
import com.xuecheng.common.domain.page.PageVO;
import com.xuecheng.common.enums.common.CommonEnum;
import com.xuecheng.common.enums.content.CourseAuditEnum;
import com.xuecheng.common.enums.content.CourseChargeEnum;
import com.xuecheng.common.exception.ExceptionCast;
import com.xuecheng.common.util.StringUtil;
import com.xuecheng.content.convert.CourseBaseConvert;
import com.xuecheng.content.entity.CourseBase;
import com.xuecheng.content.entity.CourseMarket;
import com.xuecheng.content.mapper.CourseBaseMapper;
import com.xuecheng.content.service.CourseBaseService;
import com.xuecheng.content.service.CourseMarketService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 课程基本信息 服务实现类
 * </p>
 *
 * @author itcast
 */
@Slf4j
@Service
public class CourseBaseServiceImpl extends ServiceImpl<CourseBaseMapper, CourseBase> implements CourseBaseService {

    @Autowired
    private CourseBaseService courseBaseService;
    @Autowired
    private CourseMarketService courseMarketService;

    //平台审核课程
    @Transactional
    public void approve(CourseAuditVO courseAuditVO) {
        Long courseBaseId = courseAuditVO.getCourseBaseId();
        //Long companyId = SecurityUtil.getCompanyId();
        LambdaQueryWrapper<CourseBase> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CourseBase::getId,courseBaseId);
        CourseBase one = courseBaseService.getOne(queryWrapper);
        if (ObjectUtils.isEmpty(one)){
            //课程不存在
            ExceptionCast.cast(CommonErrorCode.E_100101);
        }
        if (one.getAuditStatus().equals(CourseAuditEnum.AUDIT_PUBLISHED_STATUS.getCode())){
            throw new RuntimeException("课程已发布啦");
        }
        if (one.getAuditStatus().equals(CourseAuditEnum.AUDIT_PASTED_STATUS.getCode())){
            throw new RuntimeException("课程审核已通过啦");
        }
        if (one.getAuditStatus().equals(CourseAuditEnum.AUDIT_UNLINE_STATUS.getCode())){
            throw new RuntimeException("课程已下线啦");
        }
        LambdaUpdateWrapper<CourseBase> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(CourseBase::getAuditMind,courseAuditVO.getAuditMind());
        wrapper.set(CourseBase::getAuditStatus,courseAuditVO.getAuditStatus());
        wrapper.set(CourseBase::getAuditNums,one.getAuditNums()+1);
        wrapper.eq(CourseBase::getId,courseAuditVO.getCourseBaseId());
        boolean update = this.update(wrapper);
        if (!update){
            ExceptionCast.cast(CommonErrorCode.UNKOWN);
        }
    }

    //机构提交课程
    @Transactional
    public void commitCourseBase(Long courseId, Long companyId) {
        courseBaseService.getByCourseId(courseId,companyId);
        LambdaQueryWrapper<CourseBase> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CourseBase::getId,courseId);
        CourseBase one = this.getOne(queryWrapper);
        if (one.getAuditStatus().equals(CourseAuditEnum.AUDIT_COMMIT_STATUS.getCode())){
            throw new RuntimeException("课程已提交啦");
        }
        if (one.getAuditStatus().equals(CourseAuditEnum.AUDIT_PUBLISHED_STATUS.getCode())){
            throw new RuntimeException("课程已发布啦");
        }
        if (one.getAuditStatus().equals(CourseAuditEnum.AUDIT_PASTED_STATUS.getCode())){
            throw new RuntimeException("课程审核已通过啦");
        }
        if (one.getAuditStatus().equals(CourseAuditEnum.AUDIT_UNLINE_STATUS.getCode())){
            throw new RuntimeException("课程已下线啦");
        }
        LambdaUpdateWrapper<CourseBase> wrapper = new LambdaUpdateWrapper<>();
        //修改状态为已提交
        wrapper.set(CourseBase::getAuditStatus,CourseAuditEnum.AUDIT_COMMIT_STATUS.getCode())
                .eq(CourseBase::getId,courseId);
        boolean update = this.update(wrapper);
        if (!update){
            ExceptionCast.cast(CommonErrorCode.UNKOWN);
        }
    }
    //分页查询课程
    public PageVO queryCourseList(PageRequestParams params, QueryCourseBaseModel model,Long companyId) {
        //长度判断
        if (params.getPageSize()<1){
            params.setPageSize(PageRequestParams.DEFAULT_PAGE_SIZE);
        }
        //页数判断
        if (params.getPageNo()<1) {
            params.setPageNo(PageRequestParams.DEFAULT_PAGE_NUM);
        }
        //判断公司id
        if (ObjectUtils.isEmpty(companyId)){
            throw new RuntimeException("公司不能为空哦!");
        }
        LambdaQueryWrapper<CourseBase> queryWrapper = new LambdaQueryWrapper<>();
        //审核状态条件
        queryWrapper.eq(StringUtil.isNotBlank(model.getAuditStatus()),CourseBase::getAuditStatus,model.getAuditStatus());
        //课程名称条件
        queryWrapper.like(StringUtil.isNotBlank(model.getCourseName()),CourseBase::getName,model.getCourseName());
        //机构id
        if (StringUtil.isBlank(model.getName())) {
            queryWrapper.eq(CourseBase::getCompanyId, companyId);
        }
        //else if (model.getName().equals("平台"))
        //课程没有被逻辑删除
        queryWrapper.eq(CourseBase::getStatus,1);
        Page<CourseBase> page = new Page<>(params.getPageNo(),params.getPageSize());
        Page<CourseBase> pageResult = this.page(page, queryWrapper);
        //当前页数据
        List<CourseBase> records = pageResult.getRecords();
        List<CourseBaseDTO> dtolist = Collections.emptyList();
        if (!CollectionUtils.isEmpty(records)){
            dtolist = CourseBaseConvert.INSTANCE.entity2dtos(records);
        }
        //总数量
        long total = pageResult.getTotal();
        PageVO pageVO = new PageVO<>(dtolist, total, params.getPageNo(), params.getPageSize());

        return pageVO;
    }

    //添加新课程
    @Transactional
    public CourseBaseDTO createCourseBase(CourseBaseDTO courseBaseDTO) {
        verifyCourseMsg(courseBaseDTO);
        CourseBase courseBase = CourseBaseConvert.INSTANCE.dto2entity(courseBaseDTO);
        courseBase.setStatus(CommonEnum.USING_FLAG.getCodeInt());
        courseBase.setAuditStatus(CourseAuditEnum.AUDIT_UNPAST_STATUS.getCode());
        boolean baseResult = this.save(courseBase);
        if (!baseResult) {
            throw new RuntimeException("保存课程基础信息失败");
        }
        CourseMarket courseMarket = new CourseMarket();
        courseMarket.setCourseId(courseBase.getId());
        courseMarket.setCharge(courseBaseDTO.getCharge());
        if (CourseChargeEnum.CHARGE_YES.getCode().equals(courseBaseDTO.getCharge())) {
            BigDecimal price = courseBaseDTO.getPrice();
            if (new BigDecimal(0).compareTo(price)>-1)
            {
                throw new RuntimeException("价格不能小于等于0");
            }
            courseMarket.setPrice(price);
        }

        boolean marketResult = courseMarketService.save(courseMarket);
        if (!marketResult) {
            throw new RuntimeException("课程营销信息保存失败");
        }
        CourseBase courseBase1 = this.getById(courseBase.getId());
        CourseBaseDTO resultDTO = CourseBaseConvert.INSTANCE.entity2dto(courseBase1);
        resultDTO.setPrice(courseBaseDTO.getPrice());
        resultDTO.setCharge(courseBaseDTO.getCharge());
        return resultDTO;

    }

    //获取回显数据
    public CourseBaseDTO getByCourseId(Long courseBaseId, Long companyId) {
        LambdaQueryWrapper<CourseBase> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CourseBase::getCompanyId,companyId);
        queryWrapper.eq(CourseBase::getId,courseBaseId);
        CourseBase one = courseBaseService.getOne(queryWrapper);
        if (one==null){
            throw new RuntimeException("该项目或者该机构并不存在哦，请重新发起请求");
        }
        if (one.getAuditStatus().equals(CourseAuditEnum.AUDIT_COMMIT_STATUS)||one.getAuditStatus().equals(CourseAuditEnum.AUDIT_PASTED_STATUS)||one.getAuditStatus().equals(CourseAuditEnum.AUDIT_PUBLISHED_STATUS)){
            throw new RuntimeException("课程已提交或审核通过或者已经发布哦！");
        }

        CourseBaseDTO courseBaseDTO = CourseBaseConvert.INSTANCE.entity2dto(one);
        LambdaQueryWrapper<CourseMarket> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CourseMarket::getCourseId,courseBaseId);
        CourseMarket market = courseMarketService.getOne(wrapper);
        courseBaseDTO.setCharge(market.getCharge());
        BigDecimal price =market.getPrice();
        courseBaseDTO.setPrice(price);
        return courseBaseDTO;
    }

    //修改课程
    @Transactional
    public CourseBaseDTO modifyCourseBase(CourseBaseDTO dto) {
        verifyCourseMsg(dto);
        CourseBase courseBase = CourseBaseConvert.INSTANCE.dto2entity(dto);
        LambdaQueryWrapper<CourseBase> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CourseBase::getId, dto.getCourseBaseId());
        CourseBase one = courseBaseService.getOne(queryWrapper);
//        if (one.getCompanyId()!=dto.getCompanyId()){
//            throw new RuntimeException("两次机构不一样哦");
//        }
        if (one.getStatus()==CommonEnum.DELETE_FLAG.getCodeInt()) {
            throw new RuntimeException("该课程已经被删除了");
        }
        if (one.getAuditStatus().equals(CourseAuditEnum.AUDIT_COMMIT_STATUS.getCode())||one.getAuditStatus().equals(CourseAuditEnum.AUDIT_PASTED_STATUS.getCode())||one.getAuditStatus().equals(CourseAuditEnum.AUDIT_PUBLISHED_STATUS.getCode())){
            throw new RuntimeException("课程已提交或审核通过或者已经发布哦！不能删除");
        }
        List<CourseBase> list = courseBaseService.list();
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getId()==dto.getCourseBaseId()&&list.get(i).getId()!=one.getId()){
                throw new RuntimeException("该课程ID已存在");
            }
        }
        courseBaseService.updateById(courseBase);
        LambdaQueryWrapper<CourseMarket> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(CourseMarket::getCourseId,one.getId());
        CourseMarket market = courseMarketService.getOne(queryWrapper1);
        market.setCharge(dto.getCharge());
        if(dto.getCharge().equals(CourseChargeEnum.CHARGE_NO.getCode())){
            market.setPrice(new BigDecimal(0));
        }
        else {
            if (new BigDecimal(0).compareTo(dto.getPrice())>-1)
            {
                throw new RuntimeException("价格不能小于等于0");
            }
            market.setPrice(dto.getPrice());
        }
        courseMarketService.updateById(market);
        CourseBaseDTO courseBaseDTO = CourseBaseConvert.INSTANCE.entity2dto(courseBase);
        courseBaseDTO.setPrice(dto.getPrice());
        courseBaseDTO.setCharge(dto.getCharge());
        return courseBaseDTO;
    }

    //删除课程
    @Transactional
    public void removeCourseBase(Long courseBaseId, Long companyId) {
        //LambdaQueryWrapper<CourseMarket> wrapper = new LambdaQueryWrapper<>();
        //wrapper.eq(CourseMarket::getCourseId,courseBaseId);
        //courseMarketService.remove(wrapper);
        //CourseBase one = courseBaseService.getOne(queryWrapper);
        CourseBase courseBase = judge(courseBaseId, companyId);
        if (courseBase.getStatus()==0){
            throw new RuntimeException("该项目已被删除,不能再次删除");
        }
        LambdaUpdateWrapper<CourseBase> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.set(CourseBase::getStatus,0).eq(CourseBase::getId,courseBase.getId());
        this.update(lambdaUpdateWrapper);
    }
    public CourseBase judge(Long courseBaseId, Long companyId){
        LambdaQueryWrapper<CourseBase> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CourseBase::getCompanyId,companyId);
        queryWrapper.eq(CourseBase::getId,courseBaseId);
        CourseBase one = courseBaseService.getOne(queryWrapper);
        if (one==null){
            throw new RuntimeException("该项目或者该机构并不存在哦，请重新发起请求");
        }
        if (one.getAuditStatus().equals(CourseAuditEnum.AUDIT_COMMIT_STATUS)||one.getAuditStatus().equals(CourseAuditEnum.AUDIT_PASTED_STATUS)||one.getAuditStatus().equals(CourseAuditEnum.AUDIT_PUBLISHED_STATUS)){
            throw new RuntimeException("课程已提交或审核通过或者已经发布哦！不能删除");
        }
        return one;
    }
    //添加课程时的判断条件
    private void verifyCourseMsg(CourseBaseDTO courseBaseDTO) {
        if (ObjectUtils.isEmpty(courseBaseDTO.getCompanyId())) {
            throw new RuntimeException("公司id不能为空哦！");
        }
        if (StringUtil.isBlank(courseBaseDTO.getName())) {
            throw new RuntimeException("课程名称不能为空哦！");
        }
        if (StringUtil.isBlank(courseBaseDTO.getMt())) {
            throw new RuntimeException("课程大分类不能为空哦！");
        }
        if (StringUtil.isBlank(courseBaseDTO.getSt())) {
            throw new RuntimeException("课程小分类不能为空哦！");
        }
        if (StringUtil.isBlank(courseBaseDTO.getGrade())) {
            throw new RuntimeException("课程等级不能为空哦！");
        }
        if (StringUtil.isBlank(courseBaseDTO.getTeachmode())) {
            throw new RuntimeException("课程教学模式不能为空哦！");
        }
//        if (StringUtil.isBlank(courseBaseDTO.getUsers())) {
//            throw new RuntimeException("使用人群不能为空哦！");
//        }
        if (StringUtil.isBlank(courseBaseDTO.getCharge())) {
            throw new RuntimeException("课程收费不能为空哦！");
        }
        if (CourseChargeEnum.CHARGE_YES.getCode().equals(courseBaseDTO.getCharge())) {
            if (ObjectUtils.isEmpty(courseBaseDTO.getPrice())) {
                throw new RuntimeException("收费课程价格不能为空哦！");
            }
        }
    }
}
